<?php

class EditAction extends ActionBase {

	public $modelName = '';
	protected $_model;
	protected $_successUrl = '';
	public $updateSuccess = '操作成功';
	public $updateFailed = '操作失败';
	public $createSuccess = '操作成功';
	public $createFailed = '操作失败';
	
	public $operatesReturn = true;
	public $ajaxName = 'ajax';
	public $ajaxId = 'form';
	public $view;
	public $cascade = array();
	public $defaultAttributes = array();
	
	public $formView = array();
	
	public $pk;
	
	public function getSuccessUrl() {
		return $this->_successUrl
			? $this->_successUrl 
			: $this->_successUrl = $this->controller->createUrl(
				'admin'
			);
	}
	
	public function setSuccessUrl($url) {
		list($route, $params) = $url;
		if(!$params) $params = array();
		$this->_successUrl = $this->controller->createUrl($route, $params);
	}
	
	public function loadModel($id) {
		if(!$this->_model) {
			$id = $this->pk ? $this->pk : $id;
			$model = $this->controller->loadModel($id);
			$model->setAttributes($this->defaultAttributes, false);
			$this->_model = $model;
		}
		return $this->_model;
	}
	
	public function run($id = null) {
		$this->prepare();
		
		$c = $this->controller;
		$model = $this->loadModel($id);
		$c->operatesReturn = $this->operatesReturn;
		$this->performAjaxValidation($model);
		
		if($this->loadData($model)) {
			
			if($model->save()) {
				if(Yii::app()->request->isAjaxRequest){
					echo json_encode(array($model->tableSchema->primaryKey=>$model->primaryKey));
					Yii::app()->end();
				}
				Yii::app()->user->setFlash(FLASH::RESULT_SUCCESS, $id 
					? $this->updateSuccess
					: $this->createSuccess
				);
				$this->goSuccess();
			} else {
				Yii::app()->user->setFlash(FLASH::RESULT_FAILED, $id
					? $this->updateFailed
					: $this->createFailed
				);
			}
		}
		$c->render($this->view, array(
			'model' => $model,
			'ajaxName' => $this->ajaxName,
			'ajaxId' => $this->ajaxId,
			'cascade' => $this->cascade,
			'formView' => $this->getFormView(),
		));
	}
	
	public function getFormViewFields() {
		$fields = array();
		$userFields = isset($this->formView['fields']) ? $this->formView['fields'] : array();
		$model = $this->_model;
		
		if($this->cascade) {
			foreach($model->attributeNames() as $one) {
				if(isset($userFields['baseInfo'][$one])) {
					$fields['baseInfo'][$one] = $userFields['baseInfo'][$one];
				} else {
					$fields['baseInfo'][] = $one;
				}
			}
			if(isset($userFields['baseInfo']['_with'])) {
				foreach($userFields['baseInfo']['_with'] as $k=>$v) {
					if(is_string($k)) {
						if(isset($fields['baseInfo'][$k])) unset($fields['baseInfo'][$k]);
						$fields['baseInfo'][$k] = $v;
					} else {
						$fields['baseInfo'][] = $v;
					}
				}
			}
			$relations = $model->relations();
			foreach($this->cascade as $rName) {
				if(!isset($relations[$rName])) continue;
				if(is_string($userFields[$rName])) {
					$fields[$rName] = $userFields[$rName];
					continue;
				}
				$model = new $relations[$rName][1];
				foreach($model->attributeNames() as $one) {
					if($relations[$rName][0] == CActiveRecord::HAS_MANY) {
						$attribute = $rName.'..'.$one;
					} else {
						$attribute = $rName.'.'.$one;
					}
					if(isset($userFields[$rName][$one])) {
						$fields[$rName][$attribute] = $userFields[$rName][$one];
					} else {
						$fields[$rName][] = $attribute;
					}
				}
			}
		} else {
			foreach($model->attributeNames() as $one) {
				if(isset($userFields[$one])) {
					$fields[$one] = $userFields[$one];
				} else {
					$fields[] = $one;
				}
			}
			if(isset($userFields['_with'])) {
				foreach($userFields['_with'] as $k=>$v) {
					if(is_string($k)) {
						if(isset($fields[$k])) unset($fields[$k]);
						$fields[$k] = $v;
					} else {
						$fields[] = $v;
					}
				}
			}
		}
		
//		CVarDumper::
//		dump($fields, 11, true);die;
		
		return $fields;
	}
	
	public function getFormView() {
		$config = array_merge(array(
			'model' => $this->_model,
			'useGroup' => $this->cascade ? true : false,
			'template' => AdminModule::COMMON_VIEW.'_form',
			'activeForm' => array(
				'id' => $this->ajaxId,
				'enableAjaxValidation' => true,
			),
		), $this->formView);
		$config['fields'] = $this->getFormViewFields();
		return $config;
	}
	
	public function loadData($model) {
		if(isset($_POST[$this->modelName])) {
			$model->attributes = $_POST[$this->modelName];
			return true;
		} else {
			return false;
		}
	}
	
	public function goSuccess() {
		$this->controller->redirect($this->getSuccessUrl());
	}
	
	protected function performAjaxValidation($model)
	{
	    if(isset($_POST[$this->ajaxName]) && $_POST[$this->ajaxName]===$this->ajaxId)
	    {
	        echo CActiveFormAdv::validate($model);
	        Yii::app()->end();
	    }
	}
	
	
}

?>